<template>
	<view>
		<view style="padding: 10px; margin: 5px; background-color: #fff; border-radius: 10px">
			<view style="display: flex">
				<image class="slot-image"
					:src="activityItem?.giPrph ? getActivityItemImage(activityItem?.giPrph) : tempImageUrl"
					mode="widthFix" style="width: 100px; height: 100px"></image>
				<view style="margin-left: 10px">
					<view>{{ activityItem?.giName }}</view>
					<view style="font-size: 14px; color: #a1a3a6; margin-top: 3px">{{ activityItem?.giName }}</view>
					<view style="margin-top: 3px">
						<uni-tag :circle="true" :text="activityItem?.giGrpe + '人团'" type="error" />
					</view>
					<view style="margin-top: 12px">
						<text style="color: red">￥{{ numberFormat(activityItem?.giGppr, 2) }}</text>
						<text
							style="margin-left: 5px; font-size: 12px; text-decoration: line-through">￥{{ numberFormat(activityItem?.giInpr, 2) }}</text>
					</view>
				</view>
			</view>
			<view style="text-align: center; padding-top: 5px; border-top: 1px solid #ddd; margin-top: 10px">
				<uni-icons type="checkbox-filled" size="15" color="#1d953f"></uni-icons>
				<text style="font-size: 12px; margin-left: 5px">{{ spellOrder?.ggWcna }}已成功开团。人数不足自动退款</text>
			</view>
		</view>

		<view
			style="padding: 10px; margin: 10px 5px 5px 5px; background-color: #fff; border-radius: 10px; text-align: center">
			<view class="divider" style="width: 300px">
				<view class="line" style="border-color: red"></view>
				<view class="text" style="color: red">拼团剩余时间</view>
				<view class="line" style="border-color: red"></view>
			</view>

			<view style="margin: 0 auto 20px auto; width: 160px">
				<uni-countdown :font-size="14" second="70000" color="#FFFFFF" background-color="#007AFF"
					:show-colon="false" />
			</view>

			<view style="display: flex; ju align-items: center; justify-content: center">
				<u-avatar v-for="(item, index) in spellOrderMember" :src="item.gmAvat" size="60" style="margin-right: 20px"></u-avatar>
				<u-avatar v-for="(item, index) in spellOrder?.ggQuat - spellOrderMember?.length" icon="plus"
					fontSize="36" size="60" :style="index>0 ? 'margin-left: 20px': 'margin-left: 0'"></u-avatar>
			</view>

			<view v-if="activityItem?.giGrpe != spellOrderMember?.length" style="padding: 20px 0; font-size: 14px">
				<text
					style="color: red; font-weight: 600">还差{{ Number(activityItem?.giGrpe) - (spellOrderMember?.length || 0) }}人，即可拼团成功</text>
			</view>
			<view v-else>
				<text style="color: red; font-weight: 600">已成功拼团</text>
			</view>

			<view v-if="activityItem?.giGrpe != spellOrderMember.length" style="padding: 20px">
				<view v-if="spellOrderMember.findIndex((item) => item.gmUuid === globalUserInfo.ciUuid) === -1">
					<u-button type="error" @click="handleJoinSpellOrder">参与拼团，生成订单</u-button>
				</view>
				<view style="margin: 10px 0">
					<u-button type="warning" openType="share">邀请好友参团</u-button>
				</view>
				<view>
					<u-button type="warning" plain @click="goHome()">查看更多内容</u-button>
				</view>
			</view>
			<view v-else style="padding: 20px">
				<view style="margin: 10px 0">
					<u-button type="error" @click="handleNewSpellOrder">发起新团，创建订单</u-button>
				</view>
				<view>
					<u-button type="warning" @click="goHome()">查看更多内容</u-button>
				</view>
			</view>
		</view>
		
		<!-- 下单 -->
		<uni-popup ref="popup_order" background-color="#fff">
			<order-popup :activityItem="activityItem" :appointment="appoint" :orderType="orderType" :ggUuid="ggUuid" :closePopup="closePopup" :callback="submitOrderCallback" />
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		getItemSpellOrderByGgUuid,
		getCustOrderBySoCuidAndSoItem,
		updateActivityItemSpellOrder
	} from "../../utils/api.js";
	import {
		saveShareRecord
	} from "../../utils/helper.js";

	export default {
		data() {
			return {
				giUuid: "",
				gpUuid: "",
				ggUuid: "",
				spellOrder: {},
				spellOrderMember: [],
				activityItem: {},
				appoint: {},
				orderType: "",
				tempImageUrl: "http://jdc.jd.com/img/100x100/",
			};
		},
		async onLoad(params) {
			// uni.setEnableDebug({
			// 	enableDebug: true
			// })
			this.gpUuid = params.gpUuid || "";
			this.giUuid = params.giUuid || "";
			this.ggUuid = params.ggUuid || "";

			if (params.ggUuid) await this.loadActivityItemSpellOrder(params.ggUuid)
			
			wx.showShareMenu({
				withShareTicket: true,
				menus: ["shareAppMessage"]
			});
		},

		computed: {
			...mapGetters({
				organizationGateway: "globalInfo/organizationGateway",
				globalUserInfo: "personInfo/userInfo",
				activity: "activityInfo/activity",
				activityItem: "activityInfo/currentActivityItem",
				appointment: "activityInfo/appointment",
				defaultImageBase64: "globalInfo/defaultImageBase64",
			}),
		},

		watch: {
			appointment: {
				handler(newValue, oldValue) {
					this.appoint = newValue.find((item) => item.giUuid === this.activityItem?.giUuid) || {};
				},
				immediate: true,
				deep: true,
			},
		},

		// 转发
		onShareAppMessage(res) {
			let gpUuid = this.gpUuid || "";
			let giUuid = this.giUuid || "";
			let ggUuid = this.ggUuid || "";
			const {
				staffId,
				shUuid
			} = saveShareRecord(gpUuid);
			return {
				title: this.activityItem?.giName,
				path: `/pages/activities/detail?isJump=yes&giUuid=${giUuid}&shareId=${shUuid}&gpUuid=${gpUuid}&staffId=${staffId}&ggUuid=${ggUuid}`,
				imageUrl: this.organizationGateway + "/file/download?filepath=" + this.activityItem.giPrph[0].path,
			};
		},

		methods: {
			async loadActivityItemSpellOrder(ggUuid) {
				let res = await getItemSpellOrderByGgUuid(ggUuid);
				if (res?.ggUuid) {
					this.spellOrder = res;
					this.spellOrderMember = res?.member?.nodes;
					this.activityItem = res?.item;
				}
			},
			
			goHome() {
				uni.switchTab({
					url: "/pages/home/index",
				});
			},
			
			closePopup() {
				this.$refs.popup_order.close();
			},
			
			handleJoinSpellOrder() {
				this.orderType = "拼团订单"
				this.handlePlaceOrder()
			},
			
			async handlePlaceOrder() {
				let userInfo = uni.getStorageSync("userInfo"); // 用户信息
				let count = 0
				if (userInfo?.isNew === true) {
					if (this.activityItem.giNcby === true) {
						count = this.activityItem.giNbqu;
					} else uni.showToast({ title: "新客不能购买该项目", icon: "error", duration: 2000 });
				} else {
					if (this.activityItem.giOcby === true) {
						count = this.activityItem.giObqu;
					} else uni.showToast({ title: "老客不能购买该项目", icon: "error", duration: 2000 });
				}
				let res = await getCustOrderBySoCuidAndSoItem({ soCuid: userInfo?.ciUuid, soItem: this.activityItem?.giUuid });
				if (res.totalCount < count) {
					this.$refs.popup_order.open("bottom");
				} else {
					if (res?.nodes?.findIndex((item) => item.soStat === "待支付") !== -1) {
						uni.navigateTo({ url: `/pages/my/orders` });
					} else uni.showToast({ title: "您已超过限购次数", icon: "error", duration: 2000 });
				}
			},
			
			handleNewSpellOrder() {
				this.orderType = "参团拼单"
				this.handlePlaceOrder()
			},
			
			async submitOrderCallback(data) {
				if (!data.ggUuid) return uni.showToast({title: "拼团信息有误", icon: "error",});
				if (data.soType=== "拼团订单" || data.soType=== "参团拼单") {
					let spRes = await updateActivityItemSpellOrder({ soUuid: data.soUuid, ggUuid: data.ggUuid });
					if (spRes?.ggUuid) {
						this.$refs.popup_order.close();
						uni.showToast({
							title: "支付成功",
							icon: "success",
						});
						await this.loadActivityItemSpellOrder(spRes.ggUuid)
					}
				}
			},
			
			getActivityItemImage(giPrph) {
				let path = "";
				if (typeof giPrph === "string") path = giPrph;
				else if (Array.isArray(giPrph) && giPrph.length > 1) {
					if (typeof giPrph[0] === "string") path = giPrph[0];
					else {
						if (new Date().getUTCTime() >= this.activity.gpStti) {
							const item = giPrph.find((item) => item.display === "3");
							path = item.path || "";
						} else {
							const item = giPrph.find((item) => item.display === "2");
							path = item.path || "";
						}
					}
				}
				else if (Array.isArray(giPrph) && giPrph.length === 1) {
					if (typeof giPrph[0] === "string") {
						path = giPrph[0];
					} else path = giPrph[0].path || "";
				}
				return path ? this.organizationGateway + "/file/download?filepath=" + path : this.defaultImageBase64;
			},
		},
	};
</script>

<style>
	page {
		background-color: #eee;
	}
</style>

<style lang="scss" scoped>
	.divider {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin: 15px auto;

		.line {
			flex: 1;
			margin: 0;
			border-bottom-width: 1px;
			border-bottom-style: solid;
			width: 100%;
			transform: scaleY(0.5);
		}

		.text {
			text-align: center;
			margin: 0 15px;
		}
	}
</style>
